package com.roads.engineering.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.roads.common.constant.Constants;
import com.roads.common.constant.UserConstants;
import com.roads.common.utils.DateUtils;
import com.roads.common.utils.StringUtils;
import com.roads.project.domain.ProInstitutionDetail;
import com.roads.project.domain.ProPeriod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.roads.engineering.mapper.EngPlanScaleMapper;
import com.roads.engineering.domain.EngPlanScale;
import com.roads.engineering.service.IEngPlanScaleService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 工程计划比例Service业务层处理
 * 
 * @author nhp
 * @date 2023-03-17
 */
@Service
public class EngPlanScaleServiceImpl implements IEngPlanScaleService {

    @Autowired
    private EngPlanScaleMapper mapper;

    /**
     * 根据主键ID查询详情
     * 
     * @param id 工程计划比例主键
     * @return 工程计划比例
     */
    @Override
    public EngPlanScale getModelById(Integer id) {
        return mapper.getModelById(id);
    }

    /**
     * 查询列表
     * 
     * @param model 工程计划比例
     * @return 工程计划比例
     */
    @Override
    public List<EngPlanScale> selectModelList(EngPlanScale model) {
        return mapper.selectModelList(model);
    }

    /**
     * 查看标段下的日期是否唯一
     *
     * @param model 实体对象
     * @return 结果
     */
    @Override
    public String checkDateUnique(EngPlanScale model) {
        Integer id = StringUtils.isNull(model.getId()) ? -1 : model.getId();
        EngPlanScale search = mapper.checkDateUnique(model.getInstitutionCode(), model.getDate());
        if (StringUtils.isNotNull(search) && !search.getId().equals(id)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 生成计划
     *
     * @param detail 标段详情
     * @param userName 登录用户名称
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int gen(ProInstitutionDetail detail, String userName) {
        // 先删除标段下的计划
        mapper.deleteByCode(detail.getInnerCode());
        // 业务上报日、标段开始日期，标段截止日期
        boolean isNaturalMonth = Constants.YES.equals(detail.getIsNaturalMonth()) ? true : false;
        int businessReportingDate = detail.getBusinessReportingDate();
        Date bidBeginDate = detail.getBeginDate();
        Date bidEndDate = detail.getEndDate();
        int bidEndYear = DateUtils.getYear(detail.getEndDate());
        int bidEndMonth = DateUtils.getMonth(detail.getEndDate());
        List<EngPlanScale> planScales = new ArrayList<EngPlanScale>();
        EngPlanScale lastPlan = null;
        int periodName = 1;
        while (true) {
            // 防止死循环
            if (periodName == 100) {
                break;
            }
            EngPlanScale planScale = new EngPlanScale();
            // 第一期
            if (periodName == 1) {
                planScale.setBeginDate(bidBeginDate);
                if (isNaturalMonth) {
                    // 自然月
                    planScale.setEndDate(DateUtils.getLastDay(bidBeginDate));
                } else {
                    int beginDateDay = DateUtils.getDay(bidBeginDate);
                    Date endDate = DateUtils.getDate(DateUtils.getYear(bidBeginDate), DateUtils.getMonth(bidBeginDate), businessReportingDate);
                    if (beginDateDay < businessReportingDate) {
                        // 如果开始小于上报日
                        planScale.setEndDate(endDate);
                    } else {
                        // 如果开始大于上报日
                        planScale.setEndDate(DateUtils.addMonths(endDate, 1));
                    }
                }
            } else {
                Date lastEndDate = lastPlan.getEndDate();
                if (lastEndDate.equals(bidEndDate)) {
                    break;
                }
                Date periodBeginDate = DateUtils.addDays(lastEndDate, 1);
                planScale.setBeginDate(periodBeginDate);

                if (isNaturalMonth) {
                    Date periodEndDate = DateUtils.getLastDay(periodBeginDate);
                    int year = DateUtils.getYear(periodEndDate);
                    int month = DateUtils.getMonth(periodEndDate);
                    if (bidEndYear == year && bidEndMonth == month) {
                        planScale.setEndDate(bidEndDate);
                    } else {
                        planScale.setEndDate(periodEndDate);
                    }
                } else {
                    // 项目结束日期
                    int bidEndDay = DateUtils.getDay(bidEndDate);
                    Date periodEndDate = DateUtils.addMonths(lastPlan.getEndDate(), 1);
                    int lastYear = DateUtils.getYear(lastEndDate);
                    int lastMonth = DateUtils.getMonth(lastEndDate);
                    if (bidEndDay < businessReportingDate && (bidEndYear == lastYear && bidEndMonth == lastMonth + 1)) {
                        planScale.setEndDate(bidEndDate);
                    } else if (bidEndDay > businessReportingDate && (bidEndYear == lastYear && bidEndMonth == lastMonth)){
                        planScale.setEndDate(bidEndDate);
                    } else if (periodEndDate.getTime() > bidEndDate.getTime()) {
                        planScale.setEndDate(bidEndDate);
                    } else {
                        planScale.setEndDate(periodEndDate);
                    }
                }
            }
            planScale.setInstitutionCode(detail.getInnerCode());
            planScale.setYear(String.valueOf(DateUtils.getYear(planScale.getEndDate())));
            String month = String.valueOf(DateUtils.getMonth(planScale.getEndDate()) + 1);
            planScale.setMonth(month);
            planScale.setDate(planScale.getYear() + "-" + planScale.getMonth());
            planScale.setCreateBy(userName);
            planScale.setCreateTime(DateUtils.getNowDate());
            planScales.add(planScale);
            lastPlan = planScale;
            periodName++;
        }
        // 批量插入
        mapper.insertBatch(planScales);
        return 1;
    }

    /**
     * 新增
     * 
     * @param model 工程计划比例
     * @return 结果
     */
    @Override
    public int insert(EngPlanScale model) {
        model.setCreateTime(DateUtils.getNowDate());
        return mapper.insert(model);
    }

    /**
     * 修改
     * 
     * @param model 工程计划比例
     * @param userName 登录用户名称
     * @return 结果
     */
    @Override
    public int update(EngPlanScale model, String userName) {
        model.setUpdateTime(DateUtils.getNowDate());
        EngPlanScale beforeUpdate = mapper.getModelById(model.getId());
        // 修改前的值
        BigDecimal bumc = beforeUpdate.getMonthComplete() == null ? BigDecimal.valueOf(0) : beforeUpdate.getMonthComplete();
        BigDecimal buac = beforeUpdate.getAccumulateComplete() == null ? BigDecimal.valueOf(0) : beforeUpdate.getAccumulateComplete();
        // 现在的值
        BigDecimal monthValue = model.getMonthComplete() == null ? BigDecimal.valueOf(0) : model.getMonthComplete();
        BigDecimal accumulateValue = BigDecimal.valueOf(0);
        List<EngPlanScale> afterPlan = mapper.getAfterMonth(model.getInstitutionCode(), model.getId());
        System.out.println(afterPlan.size());
        // 值发生改变
        if (bumc.compareTo(monthValue) != 0) {
            accumulateValue = buac.subtract(bumc).add(monthValue);
            // 更新本月
            model.setAccumulateComplete(accumulateValue);
            // 更新小于本月的累计值
            if (afterPlan.size() > 0) {
                for (EngPlanScale plan : afterPlan) {
                    BigDecimal value = plan.getMonthComplete() == null ? BigDecimal.valueOf(0) : plan.getMonthComplete();
                    accumulateValue = accumulateValue.add(value);
                    plan.setAccumulateComplete(accumulateValue);
                }
            }
        }
        // 更新后面的累计值
        if (afterPlan.size() > 0) {
            // 批量修改
            mapper.updateBatch(afterPlan);
        }
        mapper.update(model);
        return 1;
    }

    /**
     * 批量删除
     * 
     * @param ids 主键集合
     * @return 结果
     */
    @Override
    public int deleteByIds(Integer[] ids) {
        return mapper.deleteByIds(ids);
    }

    /**
     * 删除
     * 
     * @param id 工程计划比例主键
     * @return 结果
     */
    @Override
    public int delete(Integer id) {
        return mapper.delete(id);
    }
}
